<template>
  <div>
    <div class="node" v-has="{action: 'group:user:list', effect: 'move'}">
      <div class="search_box topSelect">
        <div class="selectBox">
          <label>集团大客户：</label>
          <el-select
            v-model="searchs.gid"
            clearable
            @change="getPile"
            placeholder="请选择"
          >
            <el-option  v-for="item of company"
              :key="item.id"
              :value="item.id"
              :label="item.name"></el-option>
          </el-select>
        </div>
        <SearchInput
          placeholder="请输入"
          label="手机号"
          style="margin-right:20px"
          :value="searchs.phone"
          :onChange="(val) => changeSearch('phone',val)"
          :onBlur="getPile"
        />
        <SearchInput
          placeholder="请输入"
          label="车牌号"
          style="margin-right:20px"
          :value="searchs.plate"
          :onChange="(val) => changeSearch('name',val)"
          :onBlur="getPile"
        />
        <div class="searchBox1" style="margin-left: 20px">
          <el-button size="small" plain icon="el-icon-search" @click="getPile">查询</el-button>      
        </div>
      </div>
      <Panel title="集团用户成员" :intro='intro' useBack>
        <div slot='ext' class="examine">
          <el-button v-has="{action: 'group:user:add', effect: 'move'}" class="button-offt" type="success" icon="el-icon-plus" @click="()=>edit()">新增</el-button>
      </div>
      <TableEncapsulation
        slot="body"
        :tableConfig="tableConfig"
        :tableData="tableData"
      >
      <template slot="operation" slot-scope="operation">
            <el-button size="mini" icon="el-icon-edit"
              v-has="{action: 'group:user:update', effect: 'move'}"
              @click="()=>edit(operation.row)"
            >编辑</el-button>
            <el-button ize="mini" icon="el-icon-money"   type="primary" plain
              v-has="{action: 'group:user:credit', effect: 'move'}"
              v-if="operation.row.groupPayment==1"
              @click="()=>charge(operation.row)"
            >授信额度</el-button>
            <el-button size="mini" icon="el-icon-document"
              v-has="{action: 'log:group:user:wallet:list', effect: 'move'}"
              @click="()=>log(operation.row.uid)"
            >余额日志</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete"
              v-has="{action: 'group:user:delete', effect: 'move'}"
              @click="()=>remove(operation.row.uid)"
            >删除</el-button>
          </template>
          <TablePager
            slot="pager"
            v-if="pager.use"
            :size="pager.size"
            :pageChange="pageChange"
            :show-total="pager.showTotal"
            :total="pager.total"
            :current="pager.current"
          >
            <span class="demonstration">GO></span>
          </TablePager>
      </TableEncapsulation>
      </Panel>
      
    <ModalPanel 
        :visible='visible'
        title="授信额度"
        :onCancel="onCancel"
        class="bannerDialog"
        :onOk="onSubmit1">
        <div>
          <ModifyForm
            :hiddenBtn='true'
            :editColumn='editColumn'
            :updateData="updateData"
            labelWidth='100px'
            ref="charge"
            class="ModifyForm"
            :temporaryData='modalData'>
          </ModifyForm>
        </div>
      </ModalPanel>

      <!-- 添加编辑 start-->
      <ModalPanel 
        :visible='send'
        title="添加/编辑"
        :onCancel="onCancelSend"
        class="bannerDialog"
        :onOk="onSubmit">
        <div>
          <ModifyForm
            :hiddenBtn='true'
            :editColumn='editColumnSend'
            :updateData="updateDataSend"
            labelWidth='100px'
            ref="configModal"
            class="ModifyForm"
            :temporaryData='modalDataSend'>
              <div slot="timeTamp">
                <el-date-picker
                v-model="appointmentTimeSend"
                type="daterange"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="timestamp"
                :picker-options="pickerOptions"
                style="height:40px"
              ></el-date-picker>
            </div>
            <div slot="userSta">
              <select-page
              v-if="showSearch"
              :list="searchList"
              :listLoading="searchLoading"
              :nameProp="'name'"
              otherLabel='手机号'
              :params="searchPager"
              :inputValue="searchMountValue"
              :other="true"
              :otherProp="'phone'"
              :total="totalSearch"
              @getList="getSearch"
              @onChangeOrganizeValue="changeSearchInput"
              @onEnterValue="enterValue">
            </select-page>
            </div>
          </ModifyForm>
        </div>
      </ModalPanel>
      <!-- 添加编辑 end -->
    </div>
    <div style="display: none;width:100%;height:100%;margin: auto;" v-has="{action: 'group:user:list', effect: 'noPremiss'}">
      <NoPremission></NoPremission>
    </div>
  </div>
</template>
<script>
import request from "@/tools/request";
import Panel from "@/components/Panel";
import TableEncapsulation from "@/components/TableEncapsulation";
import TablePager from "@/components/Pager";
import SearchInput from "@/components/SearchInput";
import { objectFilter } from "@/tools/array";
import ModifyForm from "@/components/ModifyForm";
import ModalPanel from "@/components/ModalPanel";
// import ModalPanel from "@/components/ModalPanel";
import SelectPage from '@/components/SelectPage';
import { dateFormat } from "@/tools/time";
export default {
  name: "companyUser",
  components: {
    TableEncapsulation,
    TablePager,
    Panel,
    SearchInput,
    ModifyForm,
    ModalPanel,
    SelectPage
  },
  data() {
    return {
      intro:{
        title: '集团用户-介绍说明',
        content: `<ul><li><strong>集团用户必须注册中装天如充电小程序，由管理员配置为集团用户后才能正常使用集团支付。</strong></li><li><strong>集团用户扣费方式：</strong></li></ul><ol><li class="ql-indent-1">共享集团支付：用户完成充电后，直接从集团账户余额中扣除费用</li><li class="ql-indent-1">集团个人支付：管理员需设置用户可使用额度，不超过部分直接从集团账户余额中扣除，超过部分将从用户个人账户中扣除</li><li class="ql-indent-1">个人支付：不支持从集团账户中扣费，但能享受集团大客户专属费率</li></ol><p><br></p>`
      },
      visible: false,
      modalData: {},
      tableData: [],
      searchs:{
        component: 'companyUser',
        phone:'',
        plate:'',
        gid:'',
      },
      company:[],
      pager: {
        component: 'companyUser',
        use: true,
        total: 0,
        current: 1,
        size: 10,
        showTotal: true
      },
      operation: true,
      editColumn: [
        {
          name: "授信额度",
          prop: "credit",
          type: "text",
          required: true,
          width: 24
        },
      ],
      //分页搜索start
      searchList:[],//搜索选择框start
      searchPager: {
        pageNum: 1,
        pageSize: 10,
        showTotal: true,
        total: 0,
        condition: "",  // 输入框输入申请符合条件的数据
      },
      showSearch:false,
      searchMountValue:'',
      totalSearch: 0, // 分页的总数
      searchLoading: false,  // 搜索选择框end
      //分页搜索end
       // 添加编辑start
       pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
      },
      appointmentTimeSend: [],
      loading:false,
      edits: false,
      uid:'',
      selectValue: [],
      key:'',
      send:false,
      modalDataSend:{},
      editColumnSend: [
        {
          name: "集团",
          prop: "gid",
          type: "select",
          optionBindLabel: 'name',
          optionBindValue: 'id',
          optionList: [{'id':'','name':'请选择'}],
          onChange: (val) => {},
          required:true,
          width:24
        },
        {
          name: "选择用户",
          prop: "user",
          type: "other",
          width:24,
          required: false,
          slotName: 'userSta',
          desc:'输入用户名或手机号，按回车键搜索'
        },
        {
          name: "状态",
          prop: "state",
          type: "radio",
          optionBindLabel: 'name',
          optionBindValue: 'id',
          optionList: [{'id': 1,'name': "正常"},{'id':0, 'name':"停用"}],
          width:24,
          onChange: (val) => {},
          required: true
        },
        {
          name: "有效期",
          prop: "time",
          type: "other",
          width:24,
          required: false,
          slotName: 'timeTamp'
        },
        
        {
          name: "备注",
          width: 24,
          prop: "mark",
          type: "text",
          required: false
        },
        {
          name: "付费方式",
          prop: "groupPayment",
          type: "radio",
          optionBindLabel: 'name',
          optionBindValue: 'id',
          optionList: [{'id':0, 'name':"不支持"},{'id': 1,'name': "集团个人账户"},{'id': 2,'name': "共享集团账户"}],
          width:24,
          onChange: (val) => {},
          required: true
        },
        
      ],
      //添加编辑end
    };
  },
  created() {
    if(this.$route.query.id){
      this.searchs.gid = this.$route.query.id
    }
    // this.searchsFnc()
   
    
  },
  mounted(){
     this.getPile();
     this.companys()
  },
  computed: {
    tableConfig () {
      return {
        selection: false,
        columnConfig: [
          {
            label: "集团名称",
            type: "text",
            prop: "GName",
            align: "center"
          },
          {
            label: "用户",
            type: "text",
            prop: "UName",
            align: "center"
          },
           {
            label: "手机号",
            type: "text",
            prop: "phone",
            align: "center"
          },
          {
            label: "付费方式",
            type: "other",
            prop: "groupPayment",
            fnc: val => val == 0 ? "个人账户":val == 1 ?'集团个人账户':"共享集团账户",
            align: "center",
            // class: 'sheng2'
          },
          {
            label: "状态",
            type: "other",
            prop: "state",
            align: "center",
            fnc: val => val == 1 ? "正常" :val == 2 ? "失效":"停用",
            class:  val => val == 1 ? "agree" : val == 2 ? "time-out" : "cancel",
          },
          {
            label: "生效时间",
            type: "text",
            prop: "effectTime",
            align: "center"
          },
          {
            label: "失效时间",
            type: "text",
            prop: "invalidTime",
            align: "center"
          },
          {
            label: "集团个人账户额度",
            type: "text",
            prop: "balance",
            align: "center"
          },
          // {
          //   label: "冻结金额",
          //   type: "text",
          //   prop: "freeze",
          //   align: "center"
          // },
          {
            label: "备注",
            type: "text",
            prop: "mark",
            align: "center"
          },
          this.operation && {
            type: "operation",
            align: "center",
            label: "操作",
            width:180
          }
        ].filter(Boolean)
        }
    }
  },
  methods: {
    log(uid){
      //
      this.$router.push({ path: "/company/user/balance",query:{uid:uid} })
    },
    // 搜索选择框estart--no-page-不分页
    async getSearch(id = '') {
      this.searchLoading = true;
      let name = this.searchPager.condition 
      // let page = this.searchPager.pageNum
      id = id? id : '' 
      let search = objectFilter({ name, id })
      let data = await request({
              url: "/wx/user/select",
              method: "POST",
              data:  {
                key: name
              }
            });
      if(data.code ==0){
          this.searchList = data.list;
          console.log('this.searchList',this.searchList)
          // this.totalAgency = data.page.totalCount;
          this.searchLoading = false;
          // if(id){
          //   this.searchMountValue = data.list[0]['name']
          // }
      }else{
          this.$message("暂无数据");
          this.searchList = [];
          // this.totalAgency = 0;
          this.searchLoading = false;
      }
    },
    
    changeSearchInput(value) {
      if (value == "") { 
        // 如果输入框儿为空则清空之前选中机构后赋值的参数
        // this.searchPager.code = "";
        this.searchPager.condition = "";
        this.getSearch();
      } else {
        // 赋值
        this.searchPager.condition = value;
        this.getSearch();
      }
    },
    enterValue(val){
      console.log(val)
      this.uid = val
    },
    //搜索选择框end
    async getPile() {
      let page = this.pager.current
      let phone = this.searchs.phone
      let gid = this.searchs.gid
      let plate = this.searchs.plate
      let search = objectFilter({ phone, plate, gid, page })
      const res = await request({
        url: "/group/user/list",
        method: "POST",
        data: search
      });
      this.tableData = res.page.list
      this.pager.total = res.page.totalCount
      this.pager.current = res.page.currPage
    },
    pageChange(val) {
      this.pager.current = val;
      this.getPile();
    },
    changeSearch(key, val) {
      this.searchs[key] = val;
      this.pager.current = 1;
    },
    async companys(){
      let { list } = await request({
      url: "/company/group/select",
      method: "POST",
      data: {}
      });
      this.company  = list
      this.editColumnSend[0].optionList = list
    },
    onCancel(){
      this.visible = false
    },
    async onSubmit(){
      this.$refs['configModal'].onSubmit()
    },
    async onSubmit1(){
      this.$refs['charge'].onSubmit()
    },
    charge(rowData){
      let data = {
        credit:0, uid:rowData.uid
      }
      this.modalData = data
      this.visible = true
    },
    async updateData(values){
      let url, msg
      url = '/group/user/credit'
      msg = '编辑成功'
    let res = await request({
      url: url,
      method: 'POST',
      data: values
    })
    if (res.code !==0) return
     this.$message.success(msg)
      this.visible = false
      this.getPile()
    },
    //添加编辑start
    //用户
    async onSearch(query){
      if (query !== '') {
          this.loading = true;
          let { list } = await request({
              url: "/wx/user/select",
              method: "POST",
              data:  {
                key: query
              }
            });
            this.loading =  false
            this.selectValue = list.map(item => {
              item.value = item.id+''
              item.label = item.name
              return item
            })
        } else {
          this.selectValue = [];
        }
    },
    searchSelect(key, val){
      this[key] = val;
    },
    edit(rowData){
      if(rowData){
        this.uid = rowData.uid
        this.modalDataSend = {...rowData}
        this.edits = true
        // this.searchPager.condition = rowData.phone
        this.searchMountValue = rowData.phone
        this.appointmentTimeSend = [new Date(rowData.effectTime).getTime(), new Date(rowData.invalidTime).getTime()- 86400000 + 1000]
      }else{
        this.appointmentTimeSend = []
        this.searchMountValue = ''
        // this.searchPager.condition = ''
        this.uid = ''
        this.edits = false
        this.modalDataSend ={}
      }
      
      this.send = true
      this.showSearch = true
    },
    async onSubmitSend(){
      this.$refs['configModal'].onSubmit()
    },
    onCancelSend(){
      this.showSearch = false
      this.send = false
      
    },
    async updateDataSend(values){
      console.log('uid',)
      let invalidTime = dateFormat(this.appointmentTimeSend ? (this.appointmentTimeSend[1] + 86400000-1000) : '', 'yyyy-MM-dd HH:mm:ss')
      let effectTime = dateFormat(this.appointmentTimeSend ? this.appointmentTimeSend[0] : '', 'yyyy-MM-dd HH:mm:ss')
      let uid = this.uid
      const {state, mark, groupPayment, gid } = values
      let url = this.edits ? "/group/user/update": "/group/user/add"
      let msg = this.edits ? "编辑成功" : "添加成功"
      let res = await request({
        url: url,
        method: "POST",
        data: { effectTime, invalidTime, state, uid, mark, groupPayment, gid }
      })
      if(res.code !==0) return
        this.$message.success(msg)
        this.send = false
        this.getPile();
    },
    //添加编辑end
    remove(id){
       this.$confirm('确认删除吗', '操作确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
       let res =  await request({
          url: '/group/user/delete',
          method:"POST",
          dataType:'json',
          data: [id]
        })
        if(res.code !==0) return
        this.$message.success('删除成功')
        if(this.tableData.length===1 && this.pager.current>1)
          this.$set(this.pager,'current', this.pager.current-1)
        this.getPile()
      })
    },
  }
}
</script>
<style lang='scss' module>
.examine{
    display: flex;
    align-items: center;
    :global{
        div{
            color: #fff;
            padding: 10px;
            margin: 0 10px;
            border-radius: 2px;
            font-size: 14px;
            cursor: pointer;
            min-width: 60px;
            text-align: center;
        }
        .adopt{
                background: #409EFF;
        }
    }
}
.search_box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  :global {
    .el-input {
      width: 150px;
    }
    .el-select {
      .el-input {
        width: 90px;
      }
    }
    .el-input__icon {
      line-height: 27px;
    }
    .el-range-separator{
      line-height: 26px;
    }
  }
}

.topSelect {
  background-color: white;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}
</style>